package com.csweimei.rentmanagementtreasure.enterprise.viewModel;

import android.app.Application;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import com.csweimei.rentmanagementtreasure.R;
import com.csweimei.rentmanagementtreasure.base.AppConfig;
import com.csweimei.rentmanagementtreasure.http.entity.BaseResult;
import com.csweimei.rentmanagementtreasure.pop.PopUtils;
import com.csweimei.rentmanagementtreasure.pop.PopWheelBase;
import com.csweimei.rentmanagementtreasure.utils.GlideEngine;
import com.csweimei.rentmanagementtreasure.utils.GlideHandler;
import com.csweimei.rentmanagementtreasure.utils.ValidateUtils;
import com.csweimei.rentmanagementtreasure.utils.permission.MyCustomPopupWindow;
import com.csweimei.rentmanagementtreasure.utils.permission.RxPermissionsUtils;
import com.csweimei.rentmanagementtreasure.utils.uploadUtils.QiNiuYunBean;
import com.csweimei.rentmanagementtreasure.utils.uploadUtils.QiNiuYunUpload;
import com.csweimei.rentmanagementtreasure.utils.uploadUtils.QiNiuYunUploadCallBack;
import com.csweimei.rentmanagementtreasure.viewModel.TitleVM;
import com.csweimei.rentmanagementtreasure.weight.selAddress.MyAddressPickerView;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;

import io.reactivex.observers.DisposableObserver;
import me.goldze.mvvmhabit.base.BaseModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

public class EntAuthVM extends TitleVM {
    public EntAuthVM(@NonNull Application application, BaseModel model) {
        super(application, model);
        setTitleText("企业认证");
    }

    public ObservableField<String> imgs = new ObservableField<>();
    public ObservableField<String> businessImg = new ObservableField<>();
    public ObservableField<String> CompanyName = new ObservableField<>();
    public ObservableField<String> CompanyType = new ObservableField<>();
    public ObservableField<String> CompanyCode = new ObservableField<>();
    public ObservableField<String> LegalPerson = new ObservableField<>();
    public ObservableField<String> City = new ObservableField<>();
    public ObservableField<String> Address = new ObservableField<>();
    public ObservableField<String> faceSrc = new ObservableField<>();
    public ObservableField<String> nationSrc = new ObservableField<>();
    public ObservableField<String> fullName = new ObservableField<>();
    public ObservableField<String> IDCard = new ObservableField<>();


    public BindingCommand selImg = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            RxPermissionsUtils.file(mActivity, (RxPermissionsUtils.Accept) () -> {
                PictureSelector.create(mActivity)
                        .openGallery(SelectMimeType.ofImage())
                        .isDisplayCamera(false)
                        .setImageEngine(GlideEngine.createGlideEngine())
                        .setMaxSelectNum(1)
                        .setMinSelectNum(1)
                        .setImageSpanCount(4)
                        .forResult(new OnResultCallbackListener<LocalMedia>() {
                            @Override
                            public void onResult(ArrayList<LocalMedia> result) {
                                imgs.set(result.get(0).getRealPath());
                                GlideHandler.loadLifeWm(mActivity,imgs.get(),imageView,10);
                                getQNYToken();
                            }

                            @Override
                            public void onCancel() {

                            }
                        });
            });
        }
    });

    public BindingCommand selType = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            PopWheelBase popWheelBase = new PopWheelBase(mActivity, 1, new PopWheelBase.Click() {
                @Override
                public void click(String s) {
                    CompanyType.set(s);
                }
            });
            popWheelBase.setList1(Arrays.asList(mActivity.getResources().getStringArray(R.array.entType)));
            PopUtils.showPop(mActivity,popWheelBase,false);
        }
    });

    public BindingCommand selCity = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            View rootView = View.inflate(mActivity, R.layout.dialog_address_my, null);
            MyAddressPickerView addressView = rootView.findViewById(R.id.apvAddress);

            MyCustomPopupWindow mPopupWindow = MyCustomPopupWindow.builder()
                    .contentView(rootView)
                    .customListener((contentView) -> {
                    })
                    .activity(mActivity)
                    .isWrapHeight(true)
                    .gravity(Gravity.BOTTOM)
                    .build();
            mPopupWindow.show(0.5f);
            addressView.setOnAddressPickerSure((address, province, provinceCode, city, cityCode, area, areaCode) -> {
                if (city.equals("市辖区") || city.equals("县")) {
                    City.set(province);
                } else {
                    City.set(city);
                }
                mPopupWindow.dismiss();
            });

            addressView.setOnAddressPickerCancelListener(() -> {
                City.set("请选择");
                mPopupWindow.dismiss();
            });
        }
    });

    public BindingCommand postData = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (ValidateUtils.isEmptyString(businessImg.get())){
                ToastUtils.showShort("请上传营业执照");
                return;
            }
            if (ValidateUtils.isEmptyString(CompanyName.get())){
                ToastUtils.showShort("请选择企业类型");
                return;
            }
            if (ValidateUtils.isEmptyString(CompanyType.get())){
                ToastUtils.showShort("请输入企业名称");
                return;
            }
            if (ValidateUtils.isEmptyString(CompanyCode.get())){
                ToastUtils.showShort("请输入统一社会信用代码");
                return;
            }

            saveData();
        }
    });

    private void saveData() {
        Map<String,String> map = AppConfig.getCurMap(model);
        map.put("businessImg",businessImg.get());
        map.put("CompanyName",CompanyName.get());
        map.put("CompanyType",CompanyType.get());
        map.put("CompanyCode",CompanyCode.get());
        map.put("LegalPerson",LegalPerson.get());
        map.put("City",City.get());
        map.put("Address",Address.get());
        map.put("faceSrc",faceSrc.get());
        map.put("nationSrc",nationSrc.get());
        map.put("fullName",fullName.get());
        map.put("IDCard",IDCard.get());
        model.addcompanyauth(map)
                .compose(RxUtils.exceptionTransformer())
                .compose(RxUtils.schedulersTransformer())
                .doOnSubscribe(this)
                .subscribe(new DisposableObserver<BaseResult>() {
                    @Override
                    public void onNext(BaseResult o) {
                        if (o.issucc){
                            finish();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    ImageView imageView;
    public void setImg(ImageView img) {
        imageView = img;
    }

    /**
     * 获取七牛云token
     */
    private void getQNYToken() {
        model.getToken()
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(this)
                .doOnSubscribe(disposable -> {})
                .subscribe(new DisposableObserver<QiNiuYunBean>() {
                    @Override
                    public void onNext(QiNiuYunBean qiniuYunBean) {
                        if (ValidateUtils.isNotEmptyObjectOrString(qiniuYunBean) &&
                                ValidateUtils.isNotEmptyString(qiniuYunBean.getToken())) {
                            uploadQNY(qiniuYunBean.getToken());
                        } else {
                            ToastUtils.showShort( "请求失败，请联系管理员");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    private void uploadQNY(String token) {
        String suffix = imgs.get().substring( imgs.get().lastIndexOf("."));
        String key = "works/zgb/" + System.currentTimeMillis() + suffix;
        QiNiuYunUpload.uploadFileToQny(mActivity, imgs.get(), token, key, new QiNiuYunUploadCallBack() {
            @Override
            public void onSuccess(String url) {
                businessImg.set(url);
            }

            @Override
            public void onFail() {

            }

            @Override
            public void onProgress(String key, double progress) {

            }
        });

    }


}
